//
//  JSMBing.m
//  JSMBing
//
//  Created by 刘茂峰 on 15/12/7.
//  Copyright © 2015年 cn.sijian. All rights reserved.
//

#import "JSMBing.h"

@implementation JSMBing
-(void)layoutSubviews
{
    self.backgroundColor=[UIColor whiteColor];

}
-(void)drawRect:(CGRect)rect
{

    if (self.dataSource==nil) {
        NSException *ex=[NSException exceptionWithName:@"未设置数据源" reason:@"没有设置数据源 " userInfo:nil];
        [ex raise];
    }
    NSArray *arr;
    if ([self.dataSource respondsToSelector:@selector(JSMBingData:)]) {
        arr=[self.dataSource JSMBingData:self];
    }
    else
    {
        NSException *ex=[NSException exceptionWithName:@"未实现协议" reason:@"没有实现 JSMBingData: " userInfo:nil];
        [ex raise];
    }
    if (arr==nil||arr.count==0) {
        UIBezierPath *path2=[UIBezierPath bezierPathWithArcCenter:CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2) radius:MAX(self.bounds.size.width, self.bounds.size.height)/2-5 startAngle:0 endAngle:2*M_PI clockwise:YES];
        [path2 stroke];
        return;
    }
    CGFloat start=0;
    CGFloat end=0;
    //计算总和
    float sum=0.0;
    for (NSInteger i=0; i<arr.count; i++) {
        sum+=[arr[i] floatValue];
    }
    for (NSInteger i=0; i<arr.count; i++) {
        
        
        end=2*M_PI*([arr[i] floatValue]/sum)+start;
        
        
        UIBezierPath *path=[UIBezierPath bezierPathWithArcCenter:CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2) radius:MAX(self.bounds.size.width, self.bounds.size.height)/2-5 startAngle:start endAngle:end clockwise:YES];
        
        if ([self.dataSource respondsToSelector:@selector(JSMBingColor:andIndex:)]) {
            [[self.dataSource JSMBingColor:self andIndex:i] set];
        }
        else
        {
            [[UIColor colorWithRed:((float)arc4random_uniform(256) / 255.0) green:((float)arc4random_uniform(256) / 255.0) blue:((float)arc4random_uniform(256) / 255.0) alpha:1.0]set];
        }
        [path addLineToPoint:CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2)];
        start=end;
        [path fill];
    }
    
}
-(void)reloadData
{
    [self setNeedsDisplay];
}

@end
